package com.clstu.udp;

import java.io.IOException;
import java.net.*;

public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9998);//在9998端口准备接受数据

        byte[] data = "hello , 明天吃火锅 ~~".getBytes();
        //封装字节数组为DatagramPacket对象，用InetAddress.getByName("192.168.1.5")指定要发送的主机，最后是端口号
        DatagramPacket packet = new DatagramPacket(data,  data.length, InetAddress.getByName("192.168.1.5"), 9999);
        socket.send(packet);//发送对象

        //接受对方发送的确认吃火锅消息
        //接受到DatagramPacket对象，拆包
        socket.receive(packet);//接受到有消息发过来就继续，没有消息发过来就阻塞（等着），类似于scanner.next()等你输入
        int length = packet.getLength();
        data = packet.getData();//字节流
        System.out.println(new String(data,0,length));//输出消息

        socket.close();//关闭资源


    }
}
